<template>
  <section>
    <van-sticky>
      <PageHeader title="权限设置"/>
    </van-sticky>

    <div class="pd10 mt10 bg-color-white" v-if="role">
      <van-checkbox-group v-model="role.resource_ids">
        <div class="pt10 pb10 pr10" v-bind:style="{paddingLeft:item.layer*10 + 'px'}" v-for="(item, index) in resources" :key="index">
          <van-checkbox shape="square" :name="item.id">{{item.name}}</van-checkbox>
        </div>
      </van-checkbox-group>
    </div>

    <div style="margin: 16px;">
      <van-button round block type="info" @click="save">
        保存
      </van-button>
    </div>

  </section>
</template>

<script>
import {resourceOptionsUri, roleInfoUri, roleResourcesUri} from "../../common/api";
import PageHeader from "../componets/PageHeader";

export default {
  components: {
    PageHeader
  },
  data() {
    return {
      role: null,
      resources: []
    }
  },
  methods: {
    getRoleInfo() {
      const that = this;
      this.$http.get(roleInfoUri + '?id=' + this.$route.params.roleId).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.$toast.fail(msg);
        } else {
          that.role = data;
        }
      }, response => {
        // error callback
      })
    },
    getResources() {
      const that = this;
      this.$http.get(resourceOptionsUri).then(response => {
        let {code, msg, data} = response.body
        if (code != 0) {
          that.$toast.fail(msg);
        } else {
          that.resources = data;
        }
      }, response => {
        // error callback
      })
    },
    save() {
      const that = this;
      const postData = {
        resource_ids: that.role.resource_ids,
        id: this.$route.params.roleId
      };
      that.$http.post(roleResourcesUri, postData, {emulateJSON: true}).then(response => {
        let {msg, code, data} = response.body
        if (code != 0) {
          that.$toast.fail(msg);
        } else {
          that.$toast.success('保存成功');
        }
      }, response => {
        that.$toast.fail('发生错误');
      })
    }
  },
  mounted: function () {
    this.getRoleInfo();
    this.getResources();
  }
}
</script>

<style scoped>

</style>
